package cn.com.jrj.service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.httpclient.HttpException;

import cn.com.jrj.base.util.ConfigUtil;
import cn.com.jrj.base.util.HttpSnatch;
import cn.com.jrj.domain.Quote;

/**
 * 自选行情Service<BR>
 * 
 * var obj0={ Summary:{mstat:0,pages:1,page:1,total:3,hqtime:"20101102150436"},
 * Column:{code:0,hlp:1,id:2,lcp:3,name:4,np:5,pl:6,stp:7,tr:8}, HqData:[
 * ["600000",-0.15,"sh600000",14.65,"浦发银行",14.50,-1.02,0,1.20],
 * ["600050",-0.11,"sh600050",5.36,"中国联通",5.25,-2.05,0,0.95],
 * ["000001",0.09,"sz000001",18.57,"深发展Ａ",18.66,0.48,0,2.06] ] };
 * <p>
 * 字段含义说明:
 * </p>
 * hlp:涨跌额 , lcp:昨收, np:现价, pl:涨跌幅, stp:停牌标志 1-停牌, tr:换手率,<BR>
 * 
 * @author xiaoyu.dou
 * 
 */
public class QuoteService {
	public static final int COLUMN_ID = 2;

	public static final int COLUMN_CODE = 0;

	public static final int COLUMN_NAME = 4;

	public static final int COLUMN_NP = 5;

	public static final int COLUMN_PL = 6;

	/**
	 * 行情地址：hq.url=http://q.jrjimg.cn/?q=cn| <BR>
	 * 见config.properties
	 */
	private static final String HQ_URL = ConfigUtil.getInstance().getString("hq.url");

	private static final String DEFAULT_VAR_NAME = "fullHqData";

	/**
	 * 创建行情请求地址
	 * 
	 * @param stype
	 * @return String
	 */
	private String createHQ_URL(String stype) {
		return HQ_URL + stype + "&inc=utf-8&otc=utf-8&i=";
	}

	/**
	 * 获取行情数据(不带变量名)<BR>
	 * 股票行情查询接口参见:http://wiki.jrj.com.cn/pages/viewpage.action?pageId=24806647 <br>
	 * 查行情示例:<BR>
	 * http://q.jrjimg.cn/?q=cn|s&i=600000,600050,000001
	 * 
	 * @param stockCodes
	 * @return
	 * @throws IOException
	 * @throws HttpException
	 */
	public String getHq(String stockCodes, String stype) throws HttpException, IOException {
		HttpSnatch http = HttpSnatch.getInstance();
		String c = "";
		String url = createHQ_URL(stype) + stockCodes;
		c = http.GetWebContent(url, "utf-8", 5000);
		c = c.substring(c.indexOf("=") + 1);
		return c;
	}

	/**
	 * 批量获取股票行情(结果以List<Quote>方式返回)
	 * 
	 * @param codeArray
	 * @param batchSize
	 *            每次请求的股票数量(当数量太多时,分次处理)
	 * @return
	 * @throws HttpException
	 * @throws IOException
	 */
	public List<Quote> getQuoteList(String[] codeArray, int batchSize) throws HttpException, IOException {
		List<Quote> allQuote = new ArrayList<Quote>();
		int len = codeArray.length;
		StringBuffer ids = new StringBuffer();
		int counter = 1; // 计数器
		for (int i = 0; i < len; i++) {
			String id = codeArray[i];
			ids.append(id);
			if (((counter % batchSize) == 0) || (counter == len)) {
				// 当达到 FETCH_SIZE 或者 最后一个元素后，开始请求webservice行情
				JSONArray jsa = this.getStockPriceList(ids.toString());
				for (int j = 0; j < jsa.size(); j++) {
					JSONArray jso = jsa.getJSONArray(j);
					Quote quote = new Quote();
					quote.setStock_id(jso.getString(COLUMN_ID));
					quote.setStock_code(jso.getString(COLUMN_CODE));
					quote.setStock_name(jso.getString(COLUMN_NAME));
					quote.setPrice(jso.getDouble(COLUMN_NP));
					quote.setZdf(jso.getDouble(COLUMN_PL));
					allQuote.add(quote);
				}
				// 请求完成后，将ids重新初始化
				ids = new StringBuffer();
			} else {
				ids.append(",");
			}

			counter++; // 计数器+1
		}

		return allQuote;
	}

	/**
	 * 获取股票行情,结果以jsonArray形式返回
	 * 
	 * @param stockCodes
	 * @return
	 * @throws HttpException
	 * @throws IOException
	 */
	public JSONArray getStockPriceList(String stockCodes) throws HttpException, IOException {
		String c = this.getHq(stockCodes, "s");
		JSONObject o = JSONObject.fromObject(c);
		return o.getJSONArray("HqData");

	}

	/**
	 * 获取行情数据(带变量名, 如 var hq=.....)<BR>
	 * 股票行情查询接口参见:http://wiki.jrj.com.cn/pages/viewpage.action?pageId=24806647 <br>
	 * 查行情示例:<BR>
	 * http://q.jrjimg.cn/?q=cn|s&i=600000,600050,000001
	 * 
	 * @param stockCodes
	 * @return
	 * @throws IOException
	 * @throws HttpException
	 */
	public String getHq(String stockCodes, String varName, String stype) throws HttpException, IOException {
		HttpSnatch http = HttpSnatch.getInstance();
		String c = "";
		String url = createHQ_URL(stype) + stockCodes + "&n=" + varName;
		c = http.GetWebContent(url, "utf-8", 5000);
		return c;
	}

}
